<template>
  <text>
    <slot v-if="d > 0" name="d" :num="d">
      <text>{{ d }}天</text>
    </slot>
    <slot name="h" :num="h">
      <text>{{ h }}小时</text>
    </slot>
    <slot name="m" :num="m">
      <text>{{ m }}分</text>
    </slot>
    <!-- <text>{{ s }}秒</text> -->
  </text>
</template>

<script setup>
const props = defineProps({
  time: {
    type: String,
    default: ''
  },
  endtime: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['end']);

const timer = ref(null);
const targetDate = new Date(props.endtime).getTime();
const d = ref(0);
const h = ref(0);
const m = ref(0);
const s = ref(0);

function handleTime() {
  let now = new Date().getTime();
  if (props.time) {
    now = new Date(props.time).getTime();
  }

  if (now > targetDate) {
    if (timer.value) {
      clearInterval(timer.value);
    }
    emits('end');
    return;
  }

  const timeDifference = targetDate - now;

  d.value = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
  const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);

  h.value = hours < 10 ? `0${hours}` : hours;
  m.value = minutes < 10 ? `0${minutes}` : minutes;
  s.value = seconds < 10 ? `0${seconds}` : seconds;
}
handleTime();
if (!props.disabled) {
  timer.value = setInterval(() => {
    handleTime();
  }, 1000);
}

onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style lang="scss" scoped></style>
